﻿// Jinx AJAX Framework
// Copyright (C) 2008 Blake Hegerle
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Threading;

namespace Jinx.Utility.Timing
{
    public delegate void EndOfOperationDelegate();

    public sealed class TimeBoundOperation : IComparable<TimeBoundOperation>
    {
        private readonly TimeSpan TimeLimit;
        private bool Completed;
        private DateTime DoneTime;
        private object Sync;

        public TimeBoundOperation(TimeSpan TimeLimit)
        {
            this.TimeLimit = TimeLimit;
        }

        private TimeSpan TimeLeft
        {
            get
            {
                var Now = DateTime.UtcNow;

                if (DoneTime > Now)
                    return DoneTime - Now;
                
                throw new TimeoutException();
            }
        }

        #region IComparable<TimeBoundOperation> Members

        public int CompareTo(TimeBoundOperation other)
        {
            return DoneTime.CompareTo(other.DoneTime);
        }

        #endregion

        public event EndOfOperationDelegate OnTimeout;
        public event EndOfOperationDelegate OnCompleted;

        public void Complete()
        {
            if (Sync == null)
                throw new OperationNotStarted();

            lock (Sync)
            {
                Completed = true;
                Monitor.PulseAll(Sync);
            }
        }

        internal void Start(object Synchronizer)
        {
            Sync = Synchronizer;
            DoneTime = DateTime.UtcNow + TimeLimit;
        }

        internal bool WaitUntilEnded()
        {
            try
            {
                lock (Sync)
                {
                    if (!Completed)
                        Monitor.Wait(Sync, TimeLeft);

                    if (Completed)
                    {
                        if (OnCompleted != null)
                            OnCompleted();

                        return true;
                    }
                }
            }
            catch (TimeoutException)
            {
                if (OnTimeout != null)
                    OnTimeout();

                return true;
            }

            return false;
        }
    }
}